package com.deyou.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.deyou.DeYouApplication;
import com.deyou.R;
import com.deyou.chatting.utils.HandleResponseCode;
import com.deyou.chatting.utils.SortConvList;
import com.deyou.chatting.utils.TimeFormat;
import com.deyou.model.HomePageCityBean;
import com.deyou.model.MsgBean;
import com.deyou.widget.CircleImageView;
import com.zhy.autolayout.utils.AutoUtils;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * Created by yangyuancheng on 2017/6/14.
 */

public class MsgListAdapter extends RecyclerView.Adapter<MsgListAdapter.MsgViewHolder> {
    private int msgType; // 1-消息 2-提醒
    private Context mContext;
    private Map<String, String> mDraftMap = new HashMap<String, String>();
    private UIHandler mUIHandler = new UIHandler(this);
    private static final int REFRESH_CONVERSATION_LIST = 0x3003;
    private SparseBooleanArray mArray = new SparseBooleanArray();
    private HashMap<Conversation, Integer> mAtConvMap = new HashMap<Conversation, Integer>();
    List<Conversation> mDatas;
    private OnMsgItemClickerListener listener;

    public void setMsgType(int msgType) {
        this.msgType = msgType;
    }

    public void setmDatas(List<Conversation> mDatas) {
        this.mDatas = mDatas;
        notifyDataSetChanged();
    }

    public MsgListAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public MsgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.msg_item_layout, parent, false);
        return new MsgViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final MsgViewHolder holder, int position) {
        if (msgType == 1){
            holder.tvMsgContent.setVisibility(View.VISIBLE);
            holder.tvNotifyContent.setVisibility(View.GONE);
        } else {
            holder.tvMsgContent.setVisibility(View.GONE);
            holder.tvNotifyContent.setVisibility(View.VISIBLE);
        }
        final Conversation convItem = mDatas.get(position);
        String draft = mDraftMap.get(convItem.getId());
        //如果该会话草稿为空，显示最后一条消息
        if (TextUtils.isEmpty(draft)) {
            Message lastMsg = convItem.getLatestMessage();
            if (lastMsg != null) {
                TimeFormat timeFormat = new TimeFormat(mContext, lastMsg.getCreateTime());
                holder.tvMsgSendTime.setText(timeFormat.getTime());
                String contentStr;
                // 按照最后一条消息的消息类型进行处理
                switch (lastMsg.getContentType()) {
                    case image:
                        contentStr = mContext.getString(R.string.type_picture);
                        break;
                    case voice:
                        contentStr = mContext.getString(R.string.type_voice);
                        break;
                    case location:
                        contentStr = mContext.getString(R.string.type_location);
                        break;
                    case file:
                        contentStr = mContext.getString(R.string.type_file);
                        break;
                    case video:
                        contentStr = mContext.getString(R.string.type_video);
                        break;
                    case eventNotification:
                        contentStr = mContext.getString(R.string.group_notification);
                        break;
                    case custom:
//                        CustomContent customContent = (CustomContent) lastMsg.getContent();
//                        Boolean isBlackListHint = customContent.getBooleanValue("blackList");
//                        Boolean notFriendFlag = customContent.getBooleanValue("notFriend");
//                        if (isBlackListHint != null && isBlackListHint) {
//                            contentStr = mContext.getString(R.string.jmui_server_803008);
//                        } else {
//                            contentStr = mContext.getString(R.string.type_custom);
//                        }
                        contentStr = convItem.getLatestText();
                        break;
                    default:
                        contentStr = ((TextContent) lastMsg.getContent()).getText();
                }
                MessageContent msgContent = lastMsg.getContent();
                Boolean isRead = msgContent.getBooleanExtra("isRead");
                if (lastMsg.isAtMe()) {
                    if (null != isRead && isRead) {
                        mArray.delete(position);
                        mAtConvMap.remove(convItem);
                    } else {
                        mArray.put(position, true);
                    }
                }

                if (mArray.get(position) && DeYouApplication.isNeedAtMsg) {
                    //有人@我 文字提示
                    contentStr = mContext.getString(R.string.somebody_at_me) + contentStr;
                    SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                    builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.tvMsgContent.setText(builder);
                } else {
                    holder.tvMsgContent.setText(contentStr);
                }
            } else {
                TimeFormat timeFormat = new TimeFormat(mContext, convItem.getLastMsgDate());
                holder.tvMsgSendTime.setText(timeFormat.getTime());
                holder.tvMsgContent.setText("");
            }
        } else {
            draft = mContext.getString(R.string.draft) + draft;
            SpannableStringBuilder builder = new SpannableStringBuilder(draft);
            builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.tvMsgContent.setText(builder);
        }

        // 如果是单聊
        if (convItem.getType().equals(ConversationType.single)) {
            holder.tvMsgFrom.setText(convItem.getTitle());
            UserInfo userInfo = (UserInfo) convItem.getTargetInfo();
            if (userInfo != null && !TextUtils.isEmpty(userInfo.getAvatar())) {
                userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                    @Override
                    public void gotResult(int status, String desc, Bitmap bitmap) {
                        if (status == 0) {
                            holder.msgTypePhoto.setImageBitmap(bitmap);
                        } else {
                            holder.msgTypePhoto.setImageResource(R.drawable.jmui_head_icon);
                            HandleResponseCode.onHandle(mContext, status, false);
                        }
                    }
                });
            } else {
                holder.msgTypePhoto.setImageResource(R.drawable.jmui_head_icon);
            }
            if (convItem.getUnReadMsgCnt() > 0) {
                holder.newMsgNumber.setVisibility(View.VISIBLE);
                if (convItem.getUnReadMsgCnt() < 100) {
                    holder.newMsgNumber.setText(String.valueOf(convItem.getUnReadMsgCnt()));
                } else {
                    holder.newMsgNumber.setText(mContext.getString(R.string.hundreds_of_unread_msgs));
                }
            } else {
                holder.newMsgNumber.setVisibility(View.GONE);
            }
        }
        holder.msgItemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.msgItemClick(convItem);
            }
        });
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return null == mDatas ? 0 : mDatas.size();
    }


    /**
     * 收到消息后将会话置顶
     *
     * @param conv 要置顶的会话
     */
    public void setToTop(Conversation conv) {
        for (Conversation conversation : mDatas) {
            if (conv.getId().equals(conversation.getId())) {
                mDatas.remove(conversation);
                mDatas.add(0, conv);
                mUIHandler.removeMessages(REFRESH_CONVERSATION_LIST);
                mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
                return;
            }
        }
        //如果是新的会话
        mDatas.add(0, conv);
        mUIHandler.removeMessages(REFRESH_CONVERSATION_LIST);
        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }

    public void sortConvList() {
        SortConvList sortConvList = new SortConvList();
        Collections.sort(mDatas, sortConvList);
        notifyDataSetChanged();
    }

    public void addNewConversation(Conversation conv) {
        mDatas.add(0, conv);
        notifyDataSetChanged();
    }

    public void addAndSort(Conversation conv) {
        mDatas.add(conv);
        SortConvList sortConvList = new SortConvList();
        Collections.sort(mDatas, sortConvList);
        notifyDataSetChanged();
    }

    public void deleteConversation(Conversation conversation) {
        mDatas.remove(conversation);
        notifyDataSetChanged();
    }

    public void putDraftToMap(Conversation conv, String draft) {
        mDraftMap.put(conv.getId(), draft);
    }

    public void delDraftFromMap(Conversation conv) {
        mArray.delete(mDatas.indexOf(conv));
        mAtConvMap.remove(conv);
        mDraftMap.remove(conv.getId());
        notifyDataSetChanged();
    }

    public String getDraft(String convId) {
        return mDraftMap.get(convId);
    }

    public boolean includeAtMsg(Conversation conv) {
        if (mAtConvMap.size() > 0) {
            Iterator<Map.Entry<Conversation, Integer>> iterator = mAtConvMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Conversation, Integer> entry = iterator.next();
                if (conv == entry.getKey()) {
                    return true;
                }
            }
        }
        return false;
    }

    public int getAtMsgId(Conversation conv) {
        return mAtConvMap.get(conv);
    }

    public void putAtConv(Conversation conv, int msgId) {
        mAtConvMap.put(conv, msgId);
    }

    static class MsgViewHolder extends BaseViewHolder {
        @BindView(R.id.msg_item_layout)
        RelativeLayout msgItemLayout;
        @BindView(R.id.msg_type_photo)
        CircleImageView msgTypePhoto;
        @BindView(R.id.new_msg_number)
        TextView newMsgNumber;
        @BindView(R.id.tv_msg_from)
        TextView tvMsgFrom;
        @BindView(R.id.tv_msg_send_time)
        TextView tvMsgSendTime;
        @BindView(R.id.tv_msg_content)
        TextView tvMsgContent;
        @BindView(R.id.tv_notify_content)
        TextView tvNotifyContent;

        MsgViewHolder(View view) {
            super(view);
            AutoUtils.auto(view);
            ButterKnife.bind(this, view);
        }
    }

    static class UIHandler extends Handler {

        private final WeakReference<MsgListAdapter> mAdapter;

        public UIHandler(MsgListAdapter adapter) {
            mAdapter = new WeakReference<MsgListAdapter>(adapter);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            MsgListAdapter adapter = mAdapter.get();
            if (adapter != null) {
                switch (msg.what) {
                    case REFRESH_CONVERSATION_LIST:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

    public interface OnMsgItemClickerListener{
        void msgItemClick(Conversation conversation);
    }

    public void setOnMsgItemClick(OnMsgItemClickerListener itemClickerListener){
        this.listener = itemClickerListener;
    }
}
